﻿using Playnite.SDK.Models;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImportExporter.ImportAttributes
{
    public static class ImportFeatures
    {
        public static void DoImportFeatures(IPlayniteAPI PlayniteApi, Game game, List<GameFeature> importedFeatureList)
        {
            List<GameFeature> existedFeatureList = PlayniteApi.Database.Features.ToList();

            // 在imported中根据Id找Name（这个是一定能找到的）
            List<GameFeature> spcificationExistsFeatureList = importedFeatureList.Where<GameFeature>(item =>
            {
                if (game.FeatureIds != null)
                {
                    return game.FeatureIds.Contains(item.Id);
                }
                else
                {
                    return false;
                }
            }).ToList();
            // 在existed中根据Name找Id（这个不一定能找到，imported来的可能是新的）
            if (game.FeatureIds != null)
            {
                game.FeatureIds.Clear();
                foreach (GameFeature feature in spcificationExistsFeatureList)
                {
                    List<GameFeature> foundList = existedFeatureList.FindAll(p => p.Name.Trim().Equals(feature.Name.Trim(), StringComparison.OrdinalIgnoreCase)).ToList();
                    if (foundList.Count > 0)
                    {
                        game.FeatureIds.Add(foundList[0].Id);
                    }
                    else
                    {
                        PlayniteApi.Database.Features.Add(feature);
                        game.FeatureIds.Add(feature.Id);
                    }
                }
            }
        }
    }
}
